package com.pe.pgn.clubpgn.webapp.controller.clienteempresa;

import java.math.BigDecimal;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;

import com.pe.pgn.clubpgn.domain.ClpbClienteEmpresa;
import com.pe.pgn.clubpgn.domain.ClpdLineaCredito;
import com.pe.pgn.clubpgn.domain.beans.BNClienteEmpresa;
import com.pe.pgn.clubpgn.domain.beans.BNClienteEmpresaBusqueda;
import com.pe.pgn.clubpgn.service.ClienteEmpresaService;
import com.pe.pgn.clubpgn.service.SincronizacionFlotaService;
import com.pe.pgn.clubpgn.webapp.controller.BaseFormController;

@Controller
@RequestMapping("/clienteempresa/**")
public class ClienteEmpresaController extends BaseFormController{

	@Autowired
	private ClienteEmpresaService clienteEmpresaService;
	
	@Autowired
	private SincronizacionFlotaService sincronizacionService; 
	
	@RequestMapping("/clienteempresalist.html")
	public void listarEmpresas(@ModelAttribute("clientebusqueda") BNClienteEmpresaBusqueda clientebusqueda, 
			@RequestParam(value = "search", required = false) String search, Model model) {
		
		if(StringUtils.isNotBlank(search)){
			List<BNClienteEmpresa> empresas = clienteEmpresaService.busquedaClientesPorFiltros(
					clientebusqueda.getDeNombreEmpresa(), clientebusqueda.getDeRuc(), clientebusqueda.getLineaCreditoMinima(), 
					clientebusqueda.getLineaCreditoMaxima(), clientebusqueda.getTipoLineaCredito(), clientebusqueda.getStHabilitado());
							
			model.addAttribute("empresas",empresas);
			model.addAttribute("clientebusqueda",clientebusqueda);
			
		}else{
			List<BNClienteEmpresa> empresas = clienteEmpresaService.obtenerClienteEmpresas(Boolean.TRUE);
			model.addAttribute("clientebusqueda", new BNClienteEmpresaBusqueda());        
			model.addAttribute("empresas", empresas);
		}
	}
	
	@RequestMapping(value = "/clienteempresaform.html", method = RequestMethod.GET)
	public @ModelAttribute("clienteempresa") BNClienteEmpresa verClienteEmpresa(
		@RequestParam(value = "id", required = false) Long id, 
		HttpServletRequest request, ModelMap modelMap){
		
		if (id != null) {
			BNClienteEmpresa clienteEmpresa = clienteEmpresaService.obtenerClienteEmpresa(id,null);
			return clienteEmpresa;
		}
			
		BNClienteEmpresa clienteEmpresa = new BNClienteEmpresa();
		ClpdLineaCredito lineaCredito = new ClpdLineaCredito();
		lineaCredito.setVaSaldoLineaCredito(BigDecimal.ZERO);
		clienteEmpresa.setLineaCredito(lineaCredito);
		clienteEmpresa.setStClienteEmpresa(Boolean.TRUE);
		return clienteEmpresa;
	}
	
	
	@RequestMapping(value = "/clienteempresaform.html", method = RequestMethod.POST)
	public String guardarClienteEmpresa(@ModelAttribute("clienteempresa") BNClienteEmpresa bnclienteempresa,
			BindingResult result, SessionStatus status, HttpServletRequest request) {

		try {
			if (result.hasErrors()) {
				List<ObjectError> listError = result.getAllErrors();
				FieldError error = (FieldError)listError.get(0);
				saveError(request, error.getDefaultMessage());
				
				if(bnclienteempresa.getId() == null){
					return "redirect:clienteempresaform.html";
				}else{
					return "redirect:clienteempresaform.html?id="+bnclienteempresa.getId();
				}			
			}
			
			ClpbClienteEmpresa clienteEmpresa = new ClpbClienteEmpresa();			
	        BeanUtils.copyProperties(bnclienteempresa, clienteEmpresa);
	        
	        if (clienteEmpresa.getId() == null){
		        
	        	if(0<clienteEmpresaService.validaRuc(clienteEmpresa.getCoRuc())){
	        		saveError(request, getText("clienteempresaform.error.ruc.repetido", request.getLocale()));
	        		if(bnclienteempresa.getId() == null){
						return "redirect:clienteempresaform.html";
					}else{
						return "redirect:clienteempresaform.html?id="+bnclienteempresa.getId();
					}
	        	}	        
	        	if(0<clienteEmpresaService.validaAlias(clienteEmpresa.getDeAlias())){
	        		saveError(request, getText("clienteempresaform.error.alias.repetido", request.getLocale()));
	        		if(bnclienteempresa.getId() == null){
						return "redirect:clienteempresaform.html";
					}else{
						return "redirect:clienteempresaform.html?id="+bnclienteempresa.getId();
					}
	        	}	  
	        	if(0<clienteEmpresaService.validaRazonSocial(clienteEmpresa.getDeClienteEmpresa())){
	        		saveError(request, getText("clienteempresaform.error.razonsocial.repetido", request.getLocale()));
	        		if(bnclienteempresa.getId() == null){
						return "redirect:clienteempresaform.html";
					}else{
						return "redirect:clienteempresaform.html?id="+bnclienteempresa.getId();
					}
	        	}	  
	        	
	        } else{
	        	if(0<clienteEmpresaService.validaRuc(clienteEmpresa.getId(),clienteEmpresa.getCoRuc())){
	        		saveError(request, getText("clienteempresaform.error.ruc.repetido", request.getLocale()));
	        		if(bnclienteempresa.getId() == null){
						return "redirect:clienteempresaform.html";
					}else{
						return "redirect:clienteempresaform.html?id="+bnclienteempresa.getId();
					}
	        	}	        
	        	if(0<clienteEmpresaService.validaAlias(clienteEmpresa.getId(),clienteEmpresa.getDeAlias())){
	        		saveError(request, getText("clienteempresaform.error.alias.repetido", request.getLocale()));
	        		if(bnclienteempresa.getId() == null){
						return "redirect:clienteempresaform.html";
					}else{
						return "redirect:clienteempresaform.html?id="+bnclienteempresa.getId();
					}
	        	}	  
	        	if(0<clienteEmpresaService.validaRazonSocial(clienteEmpresa.getId(),clienteEmpresa.getDeClienteEmpresa())){
	        		saveError(request, getText("clienteempresaform.error.razonsocial.repetido", request.getLocale()));
	        		if(bnclienteempresa.getId() == null){
						return "redirect:clienteempresaform.html";
					}else{
						return "redirect:clienteempresaform.html?id="+bnclienteempresa.getId();
					}
	        	}	        	
	        }
	            	    	
        	if (clienteEmpresa.getId() != null){        		
        		sincronizacionService.guardarSyncPorClienteEmpresa(clienteEmpresa);
        	} 
        	
	        clienteEmpresaService.guardarClienteEmpresa(clienteEmpresa);
	        clienteEmpresaService.verificarTopes(clienteEmpresa);
	        
			saveMessage(request, getText("clienteempresaform.added", 
					bnclienteempresa.getDeClienteEmpresa(),request.getLocale()));
			return "redirect:clienteempresalist.html";
			
		} catch (Exception e) {
			saveError(request, getText("errors.general", request.getLocale()));
			if(bnclienteempresa.getId() == null){
				return "redirect:clienteempresaform.html";
			}else{
				return "redirect:clienteempresaform.html?id="+bnclienteempresa.getId();
			}
		}
	}
		
	@RequestMapping(value = "/clienteempresaestacionform.html", method = RequestMethod.GET)
	public @ModelAttribute("clienteempresa") BNClienteEmpresa verClienteEmpresaEstacion(
				@RequestParam(value = "id", required = true) Long id, HttpServletRequest request,ModelMap modelMap) {
	
		BNClienteEmpresa clienteEmpresa = clienteEmpresaService.obtenerClienteEmpresaEstacion(id);
		modelMap.addAttribute("contadorEstaciones",clienteEmpresa.getClienteEstaciones().size());
		return clienteEmpresa;
	}	
	
	@RequestMapping(value = "/clienteempresatopeform.html", method = RequestMethod.GET)
	public @ModelAttribute("clienteempresa") BNClienteEmpresa verClienteEmpresaTope(
				@RequestParam(value = "id", required = true) Long id, HttpServletRequest request,ModelMap modelMap) {
		
		BNClienteEmpresa clienteEmpresa= clienteEmpresaService.obtenerClienteEmpresaTope(id);
		return clienteEmpresa;
	}		
	
	@RequestMapping(value = "/eliminaclienteempresatopeform.html", method = RequestMethod.GET)
	public String eliminarTope(@RequestParam(value = "id", required = true) Long id ,
				@RequestParam(value = "idCliente", required = true) Long idCliente
				) {
		
		clienteEmpresaService.eliminarTope(id);
		return "redirect:clienteempresatopeform.html?id=" + idCliente;
	}	
	
	@RequestMapping(value = "/clienteempresatopeform.html", method = RequestMethod.POST)
	public String guardarTopeCliente(@ModelAttribute("clienteempresa") BNClienteEmpresa clienteempresa,
			BindingResult result, SessionStatus status, HttpServletRequest request) {

		try {
			if (result.hasErrors()) {
				return "/clienteempresa/clienteempresatopeform";
			}
			
			clienteEmpresaService.guardarClienteEmpresaTope(clienteempresa);
			saveMessage(request, getText("clienteempresatopeform.added",request.getLocale()));
			return "redirect:clienteempresatopeform.html?id=" + clienteempresa.getId();
			
		} catch (Exception e) {
			saveError(request, getText("errors.general", request.getLocale()));
			return "/clienteempresatope/clienteempresatopeform";
		}

	}				
	@RequestMapping(value = "/clienteempresaestacionform.html", method = RequestMethod.POST)
	public String guardarEstacionesCliente(@ModelAttribute("clienteempresa") BNClienteEmpresa clienteempresa,
			BindingResult result, SessionStatus status, HttpServletRequest request) {

		try {
			
			if (result.hasErrors()) {
				return "/clienteempresa/clienteempresaestacionform";
			}			
			
			if(!clienteempresa.getClienteEstaciones().isEmpty()){
				sincronizacionService.guardarSyncPorClienteEstacion(clienteempresa);
			}
			
			clienteEmpresaService.guardarClienteEmpresaEstacion(clienteempresa);
			saveMessage(request, getText("clienteempresaestacionform.added",request.getLocale()));
			return "redirect:clienteempresaestacionform.html?id=" + clienteempresa.getId();
			
		} catch (Exception e) {
			saveError(request, getText("errors.general", request.getLocale()));
			return "/clienteempresa/clienteempresaform";
		}
	}

	@RequestMapping(value="eliminarclienteempresa.html")
	public String inactivarClienteEmpresa(@RequestParam(value = "id", required = true) Long id, 
			HttpServletRequest request) {
		try {
			
			ClpbClienteEmpresa clienteEmpresa = new ClpbClienteEmpresa();
			clienteEmpresa.setStClienteEmpresa(false);
			clienteEmpresa.setId(id);
			
        	sincronizacionService.guardarSyncPorClienteEmpresa(clienteEmpresa);			
			clienteEmpresaService.eliminarClienteEmpresa(id);
			saveMessage(request, getText("clienteempresaform.deleted", request.getLocale()));			
			
		} catch (Exception e) {
			saveError(request, getText("errors.general", request.getLocale()));
			return "/clienteempresa/clienteempresaform";
		}
		return "redirect:clienteempresalist.html";
	}	
}

